package com.example.mynetwork2.recyclerview;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.mynetwork2.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class RecyclerVActivity extends AppCompatActivity {
    private List<NewsBean> newsList;
    RecyclerView myRecyclerView;
    MyAdapter myAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        myRecyclerView= findViewById(R.id.my_recyclerview);

        initData();
    }

    private void initData() {

        newsList= new ArrayList<>();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        myRecyclerView.setLayoutManager(linearLayoutManager);
        myRecyclerView.addItemDecoration(new SimpleDividerDecoration(this));
        myAdapter = new MyAdapter(this, newsList);
        myRecyclerView.setAdapter(myAdapter);

        if (getNewsList().size()>0){
            newsList= getNewsList();
            //把最新的值设置到适配器里面去
            myAdapter.setDatas(newsList);
            //通知适配器更新-刷新
            myAdapter.notifyDataSetChanged();

        }





    }
    //通过本地资源获取到数据
    public List<NewsBean> getNewsList(){
        List<NewsBean> list = new ArrayList<>();

        try {
            InputStream in = getAssets().open("newdata.json");
            BufferedReader bufr = new BufferedReader(new InputStreamReader(in));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = bufr.readLine()) != null) {
                builder.append(line);
            }
            in.close();
            bufr.close();
            Gson gson = new Gson();
            String json = builder.toString();
//            MyData data = gson.fromJson(json, MyData.class);
            //json = JsonTest.jsonData;
            List<NewsBean> datas = gson.fromJson(json, new TypeToken<List<NewsBean>>(){}.getType());


            for (int i = 0; i < datas.size(); i++) {
                NewsBean newsBean = datas.get(i);
                list.add(newsBean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return list;
    }
}
